//登陆注册 小仓库
import { getCode, userRegister, userLogin, getUserInfo, logOut } from '@/api'
import { setToken, getToken, removeToken } from '@/utils/token'

const state = {
  code: '',
  userInfo: {},
  token: getToken(),
}
const actions = {
  //获取验证码
  async getCode(context, phone) {
    let result = await getCode(phone)
    if (result && result.code == 200) {
      context.commit('GETCODE', result.data)
      return result.data
    }
  },
  //用户注册
  async userRegister(context, userInfo) {
    let result = await userRegister(userInfo)
    if (result.code == '200') {
      return 'OK'
    } else {
      return Promise.reject(new Error(result.message))
    }
  },
  //用户登录
  async userLogin(context, data) {
    let result = await userLogin(data)
    console.log('用户登录actions结果=', result)
    if (result && result.code == '200') {
      context.commit('USERLOGIN', result.data)
      //持久化存储token
      setToken(result.data.token)
      return 'OK'
    } else {
      if (result) {
        return Promise.reject(new Error(result.message))
      } else {
        return Promise.reject(new Error('服务异常'))
      }
    }
  },

  //获取用户信息
  async getUserInfo({ commit }) {
    let result = await getUserInfo()
    if (result.code == 200) {
      //提交用户信息
      commit('GETUSERINFO', result.data)
      return 'OK'
    } else {
      return Promise.reject(new Error('获取用户信息失败'))
    }
  },

  //退出登陆
  async logOut(context) {
    let result = await logOut()
    if (result && result.code == '200') {
      context.commit('CLEARUSERINFO')
      return 'OK'
    } else {
      return Promise.reject(new Error('请求失败'))
    }
  },
}
const mutations = {
  GETCODE(state, value) {
    state.code = value
  },
  USERLOGIN(state, value) {
    state.token = value.token
  },
  GETUSERINFO(state, value) {
    state.userInfo = value
  },
  //清空本地数据
  CLEARUSERINFO(state, value) {
    state.userInfo = {}
    state.token = ''
    removeToken()
  },
}
const getters = {}

export default {
  namespaced: 'user',
  state,
  actions,
  mutations,
  getters,
}
